from configparser import ConfigParser
import pymysql
from traceback import print_exc
import os
class ConfigReader:
    def __init__(self,file):        # 传入要读取的config文件
        self.config = ConfigParser()        # 通过ConfigParser实例化对象
        config_path = os.path.split(os.path.realpath(__file__))[0] + os.sep + file
        self.config.read(config_path,encoding='utf-8')    # 读取config文件，并加上编码格式
    def get_value(self,key):    # 通过传入的key，来获取value信息
        for section in self.config.sections():  #  遍历所有的section节
            if self.config.has_option(section,key):   # 判断当前的section中有没有包含这个key
                return self.config.get(section,key)  # 如果包含的话就返回
            else:
                return None
class DB:
    def __init__(self,database):
        self.database = database
        data_database = ConfigReader('dev_databases.ini')
        self.user = data_database.get_value(str(database) + "_user")
        self.host = data_database.get_value(str(database) + "_host")
        self.password = data_database.get_value(str(database) +"_password")
    def connect(self):
        # 创建数据库对象
        self.db = pymysql.connect(user = self.user,database=self.database,password = self.password,host=self.host,cursorclass =
            pymysql.cursors.DictCursor)
        # 创建游标
        self.cursor = self.db.cursor()

    def close(self):
        self.cursor.close()
        self.db.close()
    def selectOne(self,sql):
        self.connect()
        result = None
        try:
            self.cursor.execute(sql)
            result = self.cursor.fetchone()
            return result
        except:
            self.db.rollback()
            print_exc()     # 打印错误的堆栈信息到控制台
            return result
        finally:
            self.close()
    def selectAll(self,sql):
        self.connect()
        result = None
        try:
            self.cursor.execute(sql)
            result = self.cursor.fetchall()
            return result
        except:
            self.db.rollback()
            print_exc()  # 打印错误的堆栈信息到控制台
            return result
        finally:
            self.close()
    def __edit(self,sql):
        self.connect()
        try:
            self.cursor.execute(sql)
            self.db.commit()
        except:
            self.db.rollback()
            print_exc()
        finally:
            self.close()
    def insert(self,sql):
        return self.__edit(sql)
    def delete(self,sql):
        return self.__edit(sql)
    def update(self,sql):
        return self.__edit(sql)


if __name__ == '__main__':
    d1 = DB('crmeb')
    print(d1.selectAll('select * from eb_user_group'))










